package threading;

class SingletonLazy {
    //创建一个SingletonLazy的实例为空，volatile修饰保证指令顺序执行
    volatile private static SingletonLazy instance = null;
    //获取该实例的方法
    public static SingletonLazy getInstance(){
        //判断instance实例是否存在，存在则返回
        if (instance == null) {
            //给if语句和new操作加锁，防止多new操作
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
    //提供一个private修饰的构造方法，保证唯一性
    private SingletonLazy(){};
}

public class ThreadDemo2 {
    public static void main(String[] args) {
        //s1和s2是同一个实例
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s1 == s2);
    }
}
